package com.gzist.zzchatroomserver.interceptors;

import cn.dev33.satoken.interceptor.SaInterceptor;
import cn.dev33.satoken.jwt.StpLogicJwtForSimple;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.stp.StpLogic;
import cn.dev33.satoken.stp.StpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.ArrayList;
import java.util.List;

/**
 * 路由拦截器
 */
@Slf4j
@Configuration
public class SaTokenConfigure implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 不拦截的请求
        List<String> patterns = new ArrayList<>();
        patterns.add("/swagger-resources/**");
        patterns.add("/webjars/**");
        patterns.add("/v2/**");
        patterns.add("/swagger-ui.html");
        patterns.add("/doc.html");
        patterns.add("/admin/user/login");
        patterns.add("/client/user/login");

        // saToken拦截器
        registry.addInterceptor(new SaInterceptor(handler -> {
                    SaRouter.match("/**")
                            // 使用正确的路径排除规则
                            .notMatch(patterns.toArray(new String[0]))  // 排除Swagger接口路径
                            .check(r -> {
                                StpUtil.checkLogin();  // 检查用户登录状态
                            });
                })).addPathPatterns("/**");
    }


    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // swagger页面
        registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
        // knife4j页面
        registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
    }

    /**
     * 注入jwt模式
     */
    @Bean
    public StpLogic getStpLogicJwt() {
        return new StpLogicJwtForSimple();
    }
}

